package com.example.startproject_206shj.model;

import com.example.startproject_206shj.bean.WeatherResult;
import com.example.startproject_206shj.iface.WeatherIface;
import com.example.startproject_206shj.iface.WeatherListenser;
import com.example.startproject_206shj.service.WeatherService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Raindy on 2017/3/14.
 * 1.写实体类
 * 2.定义retrofit接口
 */

public class WeatherModel implements WeatherIface{

    private Retrofit retrofit;
    private String BASEURL="http://www.weather.com.cn/";
    private WeatherService weatherService;

    public WeatherModel() {
        //使用Retrofit-1
        retrofit = new Retrofit.Builder().baseUrl(BASEURL).addConverterFactory(GsonConverterFactory.create()).build();
    }

    @Override
    public void getWeather(String cityno, final WeatherListenser listenser) {
        //使用Retrofit-2
        weatherService = retrofit.create(WeatherService.class);
        Call<WeatherResult> call = weatherService.getResult(cityno);
        //使用Retrofit-3
        call.enqueue(new Callback<WeatherResult>() {
            @Override
            public void onResponse(Call<WeatherResult> call, Response<WeatherResult> response) {
                if(response.isSuccessful() && response.body()!=null){
                    listenser.onResponse(response.body().getWeatherinfo());
                }else {
                    listenser.onFail("onResponse fail.");
                }
            }

            @Override
            public void onFailure(Call<WeatherResult> call, Throwable t) {
                listenser.onFail(t.toString());
            }
        });
    }
}
